/**
 * Created by hama on 2016/6/12.
 */
var express = require('express');
var fs = require('fs');
var router = express.Router();


//中间件来判断用户是否登录
function sign(req, res, next){
    if(req.cookies.petname){
        next()
    }
    else{
        if(req.xhr){
            function send(code,message){
                res.status(200).json({code,message});
            }
            // req.xhr通过请求头中的X-Requested-With判断是
            // 否是Ajax请求，Ajax请求默认都带有这个请求头
            send(res, 'signin error', '请重新登录...')
        }
        else{
            res.redirect('/signin')
        }
    }
}

//用户提问
router.post('/ask',function(req,res){
    var petname = req.cookies.petname;
    function send(code,message){
        res.status(200).json({code,message});
    }
    var time = new Date();
    req.body.petname = petname;
    req.body.ip = req.ip;
    req.body.time = time;

    function saveFile(){
        var filename = `questions/${time.getTime()}.txt`;
        fs.appendFile(filename,JSON.stringify(req.body),function(err){
            if(err){
                send('file error','系统错误');
            }else{
                send('success','提交成功');
            }
        })
    }
    fs.exists('questions', exists => {
        if(exists){
            saveFile()
        }
        else{
            fs.mkdir('questions', err => {
                if(err){
                    send('file error', '抱歉，系统错误...')
                }
                else{
                    saveFile()
                }
            })
        }
    })
})
router.get('/ask',sign,function(req,res){
    res.render('ask',{
        user: req.cookies.petname
    });
})

module.exports = router